﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FMOD;

namespace _3Dsoundor2Dgraphor.Sound
{
	class SoundSource : SoundBase
	{
		public FMOD.Sound sound = null;
		public FMOD.Channel channel = null;

		private FMOD.VECTOR previousLocation;

		public SoundSource (string path, bool loop, PointF point)
		{
			result = system.createSound("c:\\sounds\\drumloop.wav", (FMOD.MODE.HARDWARE | FMOD.MODE._3D), ref sound);
			ERRCHECK(result);
			result = sound.set3DMinMaxDistance(2.0f * DISTANCEFACTOR, 10000.0f * DISTANCEFACTOR);
			ERRCHECK(result);
			if (loop)
			{
				result = sound.setMode(FMOD.MODE.LOOP_NORMAL);
				ERRCHECK(result);
			}
			else
			{
				result = sound.setMode(FMOD.MODE.LOOP_OFF);
				ERRCHECK(result);
			}
			result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, true, ref channel);
			ERRCHECK(result);
			result = channel.setPaused(true);
			ERRCHECK(result);


			previousLocation = new VECTOR();
			changePosition(point);

		}

		public void play(bool loop)
		{
			result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel);
			ERRCHECK(result);
			if (loop)
			{
				result = sound.setMode(FMOD.MODE.LOOP_NORMAL);
				ERRCHECK(result);
			}
			else
			{
				result = sound.setMode(FMOD.MODE.LOOP_OFF);
				ERRCHECK(result);
			}
		}

		public void pause()
		{
			if (channel != null) result = channel.setPaused(true);
			ERRCHECK(result);
		}

		public void changePosition(PointF point)
		{
			FMOD.VECTOR pos = new FMOD.VECTOR();
			pos.x = point.X * DISTANCEFACTOR;
			pos.z = point.Y * DISTANCEFACTOR; 
			pos.y = 0.0f;

			FMOD.VECTOR vel = new FMOD.VECTOR();
			vel.x = (pos.x - previousLocation.x) * (1000.0f / INTERFACE_UPDATETIME);
			vel.y = (pos.y - previousLocation.y) * (1000.0f / INTERFACE_UPDATETIME);
			vel.z = (pos.z - previousLocation.z) * (1000.0f / INTERFACE_UPDATETIME);

			result = channel.set3DAttributes(ref pos, ref vel);
			ERRCHECK(result);

			previousLocation = pos;
		}


	}
}
